package com.haoshuang.zhouzhoubang.ui.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.ItemChooseImageBinding
import com.luck.picture.lib.entity.LocalMedia
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.gone
import com.mufeng.libs.utils.view.imageResource
import com.mufeng.libs.utils.view.load
import com.mufeng.libs.utils.view.visible

/**
 * 图片选择适配器
 * @param data 图片选中集合
 * @param add () -> Unit 图片添加执行方法
 * @param delete (Int) -> Unit 图片删除执行方法
 * @param itemClick (Int, MutableList<LocalMedia>) -> Unit 图片点击执行方法
 * */
class ChooseImageAdapter(
    val context: Context,
    private val max: Int = 9,
    val data: MutableList<LocalMedia>,
    val add: () -> Unit,
    val delete: (Int) -> Unit,
    val itemClick: (Int, MutableList<LocalMedia>) -> Unit,
) : RecyclerView.Adapter<ChooseImageAdapter.ChooseImageViewHolder>() {

    class ChooseImageViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val binding = ItemChooseImageBinding.bind(view)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChooseImageViewHolder {
        return ChooseImageViewHolder(
            LayoutInflater.from(context).inflate(R.layout.item_choose_image, parent, false)
        )
    }

    override fun onBindViewHolder(holder: ChooseImageViewHolder, position: Int) {
        val binding = holder.binding

        // 当前位置大于图片数量并且小于最大值减1
        if (position >= data.size && position <= max - 1) {
            // 显示添加图片按钮  并隐藏删除按钮
            binding.rivImage.visible()
            binding.ivDel.gone()
            binding.ivVideo.gone()
            binding.rivImage.imageResource = R.mipmap.icon_tj_img

        } else {
            // 显示图片 并显示删除按钮
            binding.rivImage.visible()
            binding.ivDel.visible()
            if (data[position].mimeType.contains("image")){
                binding.ivVideo.gone()

            }else{


                binding.ivVideo.visible()
            }
            binding.rivImage.load(data[position].realPath)
        }

        binding.ivDel.clickWithTrigger {
            delete(position)
        }

        binding.rivImage.clickWithTrigger {
            if(position >= data.size && position <= max - 1){
                add()
            }else{
                itemClick(position, data)
            }
        }
    }

    override fun getItemCount(): Int {
        return if (data.size == 0) 1 else if (data.size >= max) max else data.size + 1
    }

}